package com.hdax.dmw.common.auth;

import cn.hutool.json.JSONUtil;
import com.hdax.dmw.common.utils.Result;
import com.hdax.dmw.common.utils.ResultGenerator;
import com.hdax.dmw.common.utils.TokenUtil;
import io.jsonwebtoken.ExpiredJwtException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

@Component
public class AuthInterceptor implements HandlerInterceptor {

    // /order/p/ticketbuyerlist .split("/")

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setContentType("application/json;charset=UTF-8");
        ServletOutputStream outputStream = response.getOutputStream();
        String token = request.getHeader("token");
        String phone = request.getHeader("phone");
        Map<String,String> tokenMap = new HashMap<>();
        String uri = request.getRequestURI();
        String[] uris = uri.split("/");
        if(uris.length>=3 && uris[2].equals("p")){
            //校验token的有效性
            try {
                tokenMap = TokenUtil.parseToken(token);
            }catch (Exception e){
                if(e instanceof ExpiredJwtException ){
                    if(redisTemplate.hasKey("token:"+phone)){
                        //置换token
                    }else{
                        //重新登录
                        Result result = ResultGenerator.genErrorResult("9999", "登录已过期，请重新登录");
                        outputStream.write(JSONUtil.toJsonStr(result).getBytes(StandardCharsets.UTF_8));
                        return false;
                    }
                }else{
                    Result result = ResultGenerator.genErrorResult("9999", "登录已过期，请重新登录");
                    outputStream.write(JSONUtil.toJsonStr(result).getBytes(StandardCharsets.UTF_8));
                    return false;
                }
            }
        }
        return true;
    }
}
